package com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.diudiutechnology.www.yadiudiu.util.http.HttpClient;
import com.diudiutechnology.www.yadiudiu.util.http.JsonTools;
import com.diudiutechnology.www.yadiudiu.util.utils.Constant;
import com.diudiutechnology.www.yadiudiu.util.utils.ImgUtils;
import com.diudiutechnology.www.yadiudiu.util.utils.MyProgressDialog;
import com.diudiutechnology.www.yadiudiu.util.utils.PermissionsChecker;
import com.diudiutechnology.www.yadiudiu.util.utils.PictureUtil;
import com.diudiutechnology.www.yadiudiu.util.utils.SelectPhotoPop;
import com.diudiutechnology.www.yadiudiu.util.utils.Sundry;
import com.diudiutechnology.www.yadiudiu.util.utils.ToastUtils;
import com.diudiutechnology.www.yadiudiu.util.utils.UserInfoUtils;
import com.diudiutechnology.www.yadiudiu.util.view.UniversalPhotoPop;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.BaseActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.LoginActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.CommodityManagementModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MerchantsTypeModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MineFragmentModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.UniversalModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyApplication;
import com.diudiutechnology.www.yadiudiu.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by Administrator on 2017/8/24.
 * 添加商品 修改商品
 */

public class AddTheGoodsActivity extends BaseActivity implements View.OnClickListener, Callback.CommonCallback<String> {
    @Bind(R.id.retur)
    LinearLayout retur;

    @Bind(R.id.title_center)
    TextView title_center;

    @Bind(R.id.button)//提交
            Button button;

    @Bind(R.id.goods_name)//商品名称
            EditText goods_name;
    @Bind(R.id.introduction)//商品简介
            EditText introduction;
    @Bind(R.id.commodity_prices)//商品价格
            EditText commodity_prices;

    @Bind(R.id.add)//商品价格
            ImageView add;//添加图片
    @Bind(R.id.classification_layout)//商品分类
            LinearLayout classification_layout;
    @Bind(R.id.classification)// 选择分类展示
            TextView classification;

    Context context;
    String pos = "0"; //0、添加商品  1、修改商品 2、展示商品
    String u_id = "";//商家ID  pos=0时 u_id 为店铺id   pos=1时 u_id 为商品id  pos=2时 u_id 为商品id
    String merchanttype = "";//类型
    String typeid = "";//类型id
    String addimg = "";//图片
    private MyProgressDialog mDialog;
    String Judge_interface = "0";//判断哪个接口   0、获取类型 1、上传图片 2、上传
    int Judge_img = 0;//图片是否点击 和 类型是否点击
    List<UniversalModel> getclasstype = new ArrayList<>();//分类
    boolean Judge = false;
    private View viewkre;
    private SelectPhotoPop selectPhotoPop;
    private DisplayImageOptions options;
    private ImageLoader imageLoader;
    List<CommodityManagementModel> buycarlist = new ArrayList<>();
    int ints = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewkre = View.inflate(this, R.layout.activity_add_the_goods, null);
        setContentView(viewkre);
        ButterKnife.bind(this);
        context = this;
        initView();
    }

    private void initView() {
        MineFragmentModel mineFragmentModel = UserInfoUtils.readUserInfo(this);
        merchanttype = mineFragmentModel.getMerchanttype();
        retur.setOnClickListener(this);
        classification_layout.setOnClickListener(this);
        button.setOnClickListener(this);
        add.setOnClickListener(this);
        options = ImgUtils.imageOptions();
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(context));
        if (getIntent() != null) {
            pos = getIntent().getStringExtra("pos");
            u_id = getIntent().getStringExtra("id");
            if (!pos.equals("0")) {
                ints = getIntent().getIntExtra("ints", 0);
                buycarlist = (List<CommodityManagementModel>) getIntent().getSerializableExtra("data");
            }
        }
        if (pos.equals("1")) {
            title_center.setText("修改商品");
            button.setText("修改");
            processdetails();
        } else if (pos.equals("2")) {
            title_center.setText("商品详情");
            button.setVisibility(View.GONE);
            processdetails();
            Judge_img = 1;
            processnNotEdit();
        }
        if (!pos.equals("2")) {
            processclasstype();
        }

    }

    //展示产品详情
    private void processdetails() {
        if (buycarlist != null && buycarlist.size() > 0) {
            CommodityManagementModel ManagementModel = buycarlist.get(ints);
            goods_name.setText(ManagementModel.getName());
            introduction.setText(ManagementModel.getIntroduction());
            classification.setText(ManagementModel.getNametype());
            commodity_prices.setText(ManagementModel.getPrice());
            addimg = ManagementModel.getImg();
            typeid = ManagementModel.getClassid();
            imageLoader.displayImage(Constant.HTTP + addimg, add, options);
        }
    }

    //不可编辑
    public void processnNotEdit() {
        goods_name.setEnabled(false);
        introduction.setEnabled(false);
        commodity_prices.setEnabled(false);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retur:
                finish();
                break;
            case R.id.classification_layout://类型选择
                if (Judge_img == 0) {
                    if (getclasstype.size() > 0) {
                        processtype();
                    } else {
                        Judge = true;
                        processclasstype();
                    }
                }

                break;
            case R.id.button://提交商品
                if (TextUtils.isEmpty(goods_name.getText().toString().trim())) {//商品名称
                    ToastUtils.show(context, getResources().getString(R.string.please_product_name));
                    return;
                }
                if (TextUtils.isEmpty(introduction.getText().toString().trim())) {//商品简介
                    ToastUtils.show(context, getResources().getString(R.string.please_introduction));
                    return;
                }
                if (TextUtils.isEmpty(classification.getText().toString().trim())) {//商品分类
                    ToastUtils.show(context, getResources().getString(R.string.please_classification));
                    return;
                }
                if (TextUtils.isEmpty(commodity_prices.getText().toString().trim())) {//商品价格
                    ToastUtils.show(context, getResources().getString(R.string.please_price));
                    return;
                }
                if (TextUtils.isEmpty(addimg)) {//商品图片
                    ToastUtils.show(context, getResources().getString(R.string.please_add));
                    return;
                }
                processupload();
                break;
            case R.id.add://添加照片
                if (Judge_img == 0) {
                    if (!PermissionsChecker.getPermissionsChecker(this, "0", 0)) {
                        if (!PermissionsChecker.getPermissionsChecker(this, "0", 2)) {
                            showSelectPicPop();
                        } else {
                            ToastUtils.show(context, "请检查是否打开储存权限");
                        }
                    } else {
                        ToastUtils.show(context, "请检查是否打开相机权限");
                    }
                }
                break;
                          /* 注释  相机*/
            case R.id.item_popupwindows_camera:
                selectPhotoPop.dismiss();
                GalleryFinal.openCamera(Constant.CAMERA, MyApplication.getInstance().initGalley(Constant.CAMERA, 1), mOnHanlderResultCallback);
                break;
            /* 注释  相册*/
            case R.id.item_popupwindows_Photo:
                selectPhotoPop.dismiss();
                GalleryFinal.openGallerySingle(Constant.GALLERYSINGLE, MyApplication.getInstance().initGalley(Constant.GALLERYSINGLE, 1), mOnHanlderResultCallback);
                break;
            /* 注释  取消*/
            case R.id.item_popupwindows_cancel:
                selectPhotoPop.dismiss();
                break;
        }
    }

    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            Bitmap bitmap = PictureUtil.decodeSampledBitmapFromFile(resultList.get(0).getPhotoPath(), Constant.WIDE, Constant.WIDE);
            String conimg = PictureUtil.saveBitmapFile(bitmap, String.valueOf(0));
            processupload(conimg);
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };

    //相册
    private void showSelectPicPop() {
        selectPhotoPop = new SelectPhotoPop(this, this);
        selectPhotoPop.showAtLocation(viewkre, Gravity.BOTTOM, 0, 0);
    }

    //绑定分类
    private void processtype() {
        UniversalPhotoPop typephoto = new UniversalPhotoPop(context, getclasstype, 1);
        typephoto.showAtLocation(viewkre, Gravity.BOTTOM, 0, 0);
        typephoto.setAddresskListener(new UniversalPhotoPop.OnAddressCListener() {
            @Override
            public void onClick(String province, String city, String area) {
                classification.setText(province);
                for (int i = 0; i < getclasstype.size(); i++) {
                    if (province.equals(getclasstype.get(i).getName())) {
                        typeid = getclasstype.get(i).getId();
                    }
                }
            }
        });
    }

    //商品分类
    private void processclasstype() {
        if (Sundry.isOpenNetwork(context)) {

            mDialog = new MyProgressDialog(context);
            Judge_interface = "0";

            String data = "";
            if (merchanttype.equals("3")) {//干洗商家
                data = Constant.CLEANINGCLASSTYPE;
            } else if (merchanttype.equals("5")) {//果蔬商家
                data = Constant.VEGETABLESCLASSTYPE;
            }

            HttpClient.classtype(data, this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    //上传图片
    private void processupload(String upload) {
        if (Sundry.isOpenNetwork(context)) {
            Judge_interface = "1";
            mDialog = new MyProgressDialog(context);
            HttpClient.upload(upload, this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    //商品上传
    private void processupload() {
        if (Sundry.isOpenNetwork(context)) {
            mDialog = new MyProgressDialog(context);
            Judge_interface = "2";
            String data = "";
            if (merchanttype.equals("3")) {//干洗商家
                if (pos.equals("0")) {//产品上传
                    data = Constant.CLEANINGUPLOAD;
                } else {
                    data = Constant.CLEANINGUPDATE;//产品修改
                }
            } else if (merchanttype.equals("5")) {//果蔬商家
                if (pos.equals("0")) {//产品上传
                    data = Constant.VEGETABLESUPLOAD;
                } else {
                    data = Constant.VEGETABLESUPDATE;//产品修改
                }
            }
//            String longitude = MyApplication.getInstance().getLongitude()+"";
//            String latitude = MyApplication.getInstance().getLatitude()+"";
//            String addrStr = MyApplication.getInstance().getAddrStr();
            HttpClient.Cleaning(data, pos, u_id, typeid, goods_name.getText().toString().trim(),
                    addimg, commodity_prices.getText().toString().trim(), introduction.getText().toString().trim(),
                    this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }


    @Override
    public void onSuccess(String result) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        System.out.println("stringmd5result" + result);
        List<MerchantsTypeModel> getnote = JsonTools.getmerchanttype(result);
        if (getnote != null || getnote.size() > 0) {
            String error = getnote.get(0).getError();
            String mssage = getnote.get(0).getMssage();
            if (error.equals("200")) {
                String content = getnote.get(0).getResult();
                if (Judge_interface.equals("0")) {//商品分类
                    getclasstype = JsonTools.getclasstype(content);
                    if (Judge) {
                        processtype();
                    }
                } else if (Judge_interface.equals("1")) {//图片
                    addimg = content;
                    imageLoader.displayImage(Constant.HTTP + content, add, options);
                } else if (Judge_interface.equals("2")) {//上传修改
                    finish();
                    ToastUtils.show(context, mssage);
                }
            } else if (error.equals("105")) {
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
                ToastUtils.show(context, mssage);
            } else {
                ToastUtils.show(context, mssage);
            }
        }
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onCancelled(CancelledException cex) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onFinished() {

    }
}
